package com.ai.ly.goodsautocat.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

public class ReadWriteFile {
    
    public static String read(String filePath) {
        return read(new File(filePath));
    }

    public static String read(File file) {
        if (!file.exists()) {
            return "";
        }

        StringBuilder result = new StringBuilder();
        try {
            BufferedReader e = new BufferedReader(new FileReader(file));
            String lineContent=null;
            while ((lineContent = e.readLine()) != null) {
                
                //BufferedReader.readLine()读取文件第一行会出现bug，首行第一个字符会是一个空字符
                char s = lineContent.trim().charAt(0);
                // 65279是空字符
                if (s == 65279) {
                    if (lineContent.length() > 1) {
                        lineContent = lineContent.substring(1);
                    }
                }
                
                result.append(lineContent);
            }
            e.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result.toString();
    }

    public static void write(File file, String content, boolean isAppend) {
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter filewriter = new FileWriter(file, isAppend);
            BufferedWriter bw = new BufferedWriter(filewriter);
            bw.write(content);
            bw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
